package com.andersen.web.controller;

import com.andersen.database.entity.EmployeeEntity;
import com.andersen.database.entity.UserEntity;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Georg on 3/4/14.
 */

@Controller
public class EmployeesController extends AbstractController{

    private static final int SC_OK = 200;
    private static final int SC_INTERNAL_SERVER_ERROR = 500;

    @RequestMapping(value = "/employees", method = RequestMethod.GET)
    public String openSelectPage(ModelMap map) {


        return "employees";
    }

    @RequestMapping(value = "/a_employees", method = RequestMethod.GET)
    public @ResponseBody
    void getUserList(HttpServletRequest req, HttpServletResponse response) throws IOException {

        int offset = Integer.parseInt(req.getParameter("iDisplayStart"));
        int count = Integer.parseInt(req.getParameter("iDisplayLength"));
        int sortNum = Integer.parseInt(req.getParameter("iSortCol_0"));
        boolean sortDir = ("asc".equals(req.getParameter("sSortDir_0")));

        boolean discharge = Boolean.parseBoolean(req.getParameter("discharge"));
        ArrayList<EmployeeEntity> emplList = employeeService.getQueryEmployees(offset, count, sortNum +1 , sortDir, discharge); // sortNum +1 - c учётом id

        JSONArray arr = new JSONArray();
        for(int i=0;i<emplList.size();i++) {
            JSONObject jobj = new JSONObject();
            jobj.accumulate("DT_RowId", emplList.get(i).getId());
            jobj.accumulate("name", emplList.get(i).getName());
            jobj.accumulate("surname", emplList.get(i).getSurname());
            jobj.accumulate("patronymic", emplList.get(i).getPatronymic());
            jobj.accumulate("position", emplList.get(i).getPosition());
            jobj.accumulate("skype", emplList.get(i).getSkype());
            jobj.accumulate("phone", emplList.get(i).getPhone());
            jobj.accumulate("office", emplList.get(i).getOffice().getName());
            jobj.accumulate("discharge",emplList.get(i).isDischarged());
            arr.add(jobj);
        }
        JSONObject result = new JSONObject();
        result.accumulate("aaData", arr);
        result.accumulate("sEcho", req.getParameter("sEcho"));
        long tableSize = employeeService.getEmployeeCount();
        result.accumulate("iTotalRecords", String.valueOf(tableSize));
        result.accumulate("iTotalDisplayRecords", String.valueOf(tableSize));

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(result.toString());
        LOG.info("ajax processed. WOO");
        LOG.info(result.toString());
    }

    @RequestMapping(value = "/a_load_empl_delete_dialog", method = RequestMethod.GET)
    public String loadDeleteDialog(@RequestParam(value = "id", required=true) String emplId,
                                   ModelMap map) throws IOException {

        EmployeeEntity empl = employeeService.getEmployee(Long.parseLong(emplId));

        map.addAttribute("emplId", emplId);
        map.addAttribute("SecFirstPatr",empl.getSurname()+" "+empl.getName()+" "+empl.getPatronymic());
        map.addAttribute("Position",empl.getPosition());

        return "templates/dialog_delete_employee";
    }

    @RequestMapping(value = "/delete_employee", method = RequestMethod.POST)
    public void changeRoles(@RequestParam(value = "emplId", required = true) String id, HttpServletResponse response) {

        long EmplId = Long.parseLong(id);

        if(employeeService.dischargeEmployee(EmplId))
            response.setStatus(SC_OK);
        else
            response.setStatus(SC_INTERNAL_SERVER_ERROR);
    }

    @RequestMapping(value = "/a_check_if_acc_exists", method = RequestMethod.GET)
    public @ResponseBody void checkIfAccountExists(@RequestParam(value = "emplId", required = true) String id,
                                                   HttpServletResponse response) throws IOException {
        long emplId = Long.parseLong(id);
        UserEntity user = userService.getUserByEmployeeId(emplId);
        boolean exists = (user != null);
        JSONObject result = new JSONObject();
        result.accumulate("exists", exists);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(result.toString());

    }



}
